package com.t2t.top.controller;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import com.t2t.top.util.GsonUtils;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/log")
public class LogController extends BaseController {
    org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping("/changeLevel")
    public String changeLevel(@RequestParam("name") String name, @RequestParam("level") String level) {
        logger.info("name:{},level:{}", name, level);
        Logger log = (Logger) logger;
        Logger logger = log.getLoggerContext().getLogger(name);
        logger.setLevel(Level.toLevel(level));
        return list();
    }

    @RequestMapping("/list")
    public String list() {
        Logger log = (Logger) logger;
        List<Logger> loggers = log.getLoggerContext().getLoggerList();
        List<Map> list = new ArrayList();
        for (int i = 0; i < loggers.size(); i++) {
            Map map = new HashMap();
            Logger l = loggers.get(i);
            map.put("name", l.getName());
            map.put("level", l.getLevel() == null ? "" : MessageFormat.format("<font style='color:red'>{0}</font>", l.getLevel().toString()));
            list.add(map);
        }

        this.getRequest().setAttribute("list", list);
        this.getRequest().setAttribute("json", GsonUtils.toJson(log.getLoggerContext().getTurboFilterList()));
        this.getRequest().setAttribute("birth", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(log.getLoggerContext().getBirthTime()));
        return "log/list";
    }


}  